package com.easypan.Service.impl;


import com.easypan.Service.FileInfoService;
import com.easypan.Service.FileShareService;
import com.easypan.entity.constants.Constants;
import com.easypan.entity.dto.SessionShareDto;
import com.easypan.entity.dto.SessionwebUserDto;
import com.easypan.entity.po.FileInfo;
import com.easypan.entity.po.FileShare;
import com.easypan.entity.po.UserInfo;
import com.easypan.entity.query.FileInfoQuery;
import com.easypan.entity.query.FileShareQuery;
import com.easypan.entity.query.SimplePage;
import com.easypan.entity.vo.PaginationResultVO;
import com.easypan.entity.vo.R;
import com.easypan.entity.vo.ShareInfoVO;
import com.easypan.enums.*;
import com.easypan.exception.BusinessException;

import com.easypan.mapper.FileInfoMapper;
import com.easypan.mapper.FileShareMapper;
import com.easypan.mapper.UserMapper;
import com.easypan.util.CopyTools;
import com.easypan.util.DateUtil;
import com.easypan.util.StringTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;


/**
 * 分享信息 业务接口实现
 */
@Service("fileShareService")
public class FileShareServiceImpl implements FileShareService {

    @Resource
    private FileShareMapper<FileShare, FileShareQuery> fileShareMapper;
    @Resource
    private UserMapper userMapper;
    @Autowired
    private FileInfoMapper fileInfoMapper;
    @Autowired
    FileInfoService fileInfoService;

    /**
     * 根据条件查询列表
     */
    @Override
    public List<FileShare> findListByParam(FileShareQuery param) {
        return this.fileShareMapper.selectList(param);
    }

    /**
     * 根据条件查询列表
     */
    @Override
    public Integer findCountByParam(FileShareQuery param) {
        return this.fileShareMapper.selectCount(param);
    }

    /**
     * 分页查询方法
     */
    @Override
    public PaginationResultVO<FileShare> findListByPage(FileShareQuery param) {
        int count = this.findCountByParam(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

        SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
        param.setSimplePage(page);
        List<FileShare> list = this.findListByParam(param);
        PaginationResultVO<FileShare> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
        return result;
    }

    /**
     * 新增
     */
    @Override
    public Integer add(FileShare bean) {
        return this.fileShareMapper.insert(bean);
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<FileShare> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.fileShareMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或者修改
     */
    @Override
    public Integer addOrUpdateBatch(List<FileShare> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.fileShareMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 根据ShareId获取对象
     */
    @Override
    public FileShare getFileShareByShareId(String shareId) {
        return this.fileShareMapper.selectByShareId(shareId);
    }

    /**
     * 根据ShareId修改
     */
    @Override
    public Integer updateFileShareByShareId(FileShare bean, String shareId) {
        return this.fileShareMapper.updateByShareId(bean, shareId);
    }

    /**
     * 根据ShareId删除
     */
    @Override
    public Integer deleteFileShareByShareId(String shareId) {
        return this.fileShareMapper.deleteByShareId(shareId);
    }

    @Override
    public R shareFile(SessionwebUserDto sessionwebUserDto, String fileId, Integer validType, String code) {

        //1.数据库筛值
        FileShare fileShare=new FileShare();
        fileShare.setFileId(fileId);
        fileShare.setUserId(String.valueOf(sessionwebUserDto.getUserId()));
        fileShare.setShareId(StringTools.getRandomString(Constants.LENGTH_15));
       fileShare.setShareTime(new Date());
        ShareValidTypeEnums shareValidTypeEnums = ShareValidTypeEnums.getByType(validType);
        //计算过期时间
        //只有不是永久过期才计算
        if(shareValidTypeEnums != ShareValidTypeEnums.FOREVER)
        {
            //需要设置过期时间
            fileShare.setExpireTime(DateUtil.getAfterDate(shareValidTypeEnums.getDays()));

        }
        fileShare.setShowCount(0);
        //code
        if(code==null)
        {
            fileShare.setCode(StringTools.getRandomString(5));
        }else {
            fileShare.setCode(code);
        }
        fileShareMapper.insert(fileShare);
        return R.success(fileShare);
    }

    @Override
    @Transactional
    public R cancelShare(SessionwebUserDto sessionwebUserDto, String shareIds) {
       //取消分享也就是删除数据库 ->shareids拆分->sql->for循环
        //
        String[] split = shareIds.split(",");
     fileShareMapper.deleteFileShareBatch(split, String.valueOf(sessionwebUserDto.getUserId()));

        return R.success("删除成功");
    }

    @Override
    public R getShareLoginInfo(HttpSession session,String shareId) {
        //too 这个信息 很有可能会多次查数据库 --我们可以对该访问进行限制--
       //1.判断是否有验证码信息
        SessionShareDto attribute = (SessionShareDto) session.getAttribute(Constants.SESSION_SHARE_KEY + shareId);
if(attribute==null)
{
return R.success(null);
}
//1.5 查询分享的文件
        ShareInfoVO shareInfoVO = getShareInfoCommon(shareId);
        //2.判断登录的是本人还是其他 -



SessionwebUserDto sessionwebUserDto= (SessionwebUserDto) session.getAttribute(Constants.SESSION_KEY);
        if(sessionwebUserDto!=null&&sessionwebUserDto.getUserId()==Integer.valueOf(attribute.getShareUserId()))
        {
//给一个true
            shareInfoVO.setCurrentUser(true);
        }else
        {
shareInfoVO.setCurrentUser(false);
            //给一个假
        }

        return R.success(shareInfoVO);

        //too 这里的返回类 返回的信息太多了

    }

    private ShareInfoVO getShareInfoCommon(String shareId) {
        FileShare fileShare = fileShareMapper.selectByShareId(shareId);
        //判断是否过期
        if(fileShare==null || (fileShare.getExpireTime() != null && new Date().after(fileShare.getExpireTime())))
        {
            return null;
        }
        //判断文件状态
        ShareInfoVO shareInfoVO = CopyTools.copy(fileShare, ShareInfoVO.class);

        //查询文件信息
        FileInfo fileInfo= (FileInfo) fileInfoMapper.selectByFileIdAndUserId(fileShare.getFileId(),fileShare.getUserId());
        if (null == fileInfo || !FileDelFlagEnums.USING.getFlag().equals(fileInfo.getDelFlag())) {
            throw new BusinessException(ResponseCodeEnum.CODE_902);
        }
        UserInfo userInfo = userMapper.selectByuserid(Integer.parseInt(fileShare.getUserId()));
        shareInfoVO.setUserId(userInfo.getUserId());
        shareInfoVO.setAvatar(userInfo.getQqAvatar());
        shareInfoVO.setNickName(userInfo.getNickName());
        shareInfoVO.setFileName(fileInfo.getFileName());
        return shareInfoVO;
    }

    @Override
    public R getShareInfo(String shareId, HttpSession session) {
      //查询文件信息
        if(shareId==null)
        {
            return R.success("参数出错");
        }
        FileShare fileShare = fileShareMapper.selectByShareId(shareId);
        //判断是否过期
        if(fileShare==null || (fileShare.getExpireTime() != null && new Date().after(fileShare.getExpireTime())))
        {
          return   R.error("文件分享已经过期");
        }
         ///查询文件信息 --根据file 文件id 和user查
        FileInfo fileInfo  = (FileInfo) fileInfoMapper.selectByFileIdAndUserId(fileShare.getFileId(), fileShare.getUserId());
        if(fileInfo==null)
        {
            return  R.error("文件信息出错");
        }
        ShareInfoVO shareInfoVO = CopyTools.copy(fileInfo, ShareInfoVO.class);
        UserInfo userInfo = userMapper.selectByuserid(Integer.parseInt(fileShare.getUserId()));

        shareInfoVO.setUserId(String.valueOf(userInfo.getUserId()));
        shareInfoVO.setAvatar(userInfo.getQqAvatar());
        shareInfoVO.setNickName(userInfo.getNickName());
        shareInfoVO.setFileName(fileInfo.getFileName());

        return R.success(shareInfoVO);
    }

    @Override
    public R checkShareCode(String shareId, HttpSession session, String code) {
    //判断code
        //放入seiion
          //更新浏览次数
        //检验分享的文件是否存在并且是否是否过期
        FileShare fileShare = fileShareMapper.selectByShareId(shareId);
        if(fileShare==null || (fileShare.getExpireTime() != null && new Date().after(fileShare.getExpireTime())))
        {
            return   R.error("文件分享已经过期");
        }
        //判断 code
        if(!code.equals(fileShare.getCode()))
        {
            return  R.error("提取码错误");
        }
        //更新浏览次数 +写入seiion
        fileShareMapper.updateShareShowCount(shareId);
        SessionShareDto sessionShareDto=new SessionShareDto();
        sessionShareDto.setShareId(fileShare.getShareId());
        sessionShareDto.setShareUserId(fileShare.getUserId());
        sessionShareDto.setFileId(fileShare.getFileId());
       sessionShareDto.setExpireTime(fileShare.getExpireTime());
       //存入seiion
        session.setAttribute(Constants.SESSION_SHARE_KEY + shareId, sessionShareDto);

        return R.success("");
    }

    @Override
    public R loadFileList(String shareId, HttpSession session, String filePid) {
        //拿取seioon判断 ->
        SessionShareDto sessionShareDto = checkShare(session, shareId);
        //防止乱给pid

        //查询
        FileInfoQuery fileInfoQuery=new FileInfoQuery();
        fileInfoQuery.setFilePid(filePid);
        fileInfoQuery.setUserId(Integer.valueOf(sessionShareDto.getShareUserId()));
        if(filePid.equals("0"))
        {
            fileInfoQuery.setFileId(sessionShareDto.getFileId());
        }
        PaginationResultVO<FileInfo> listByPage = fileInfoService.findListByPage(fileInfoQuery);
        return R.success(listByPage);
    }

    @Override
    public R getFolderInfo(String shareId, HttpSession session, String path) {
        //判断seioon

        SessionShareDto shareDto = checkShare(session, shareId);
        String[] pathArray = path.split("/");//拿取每一个层级目录
        FileInfoQuery infoQuery = new FileInfoQuery();
        infoQuery.setUserId(Integer.parseInt(shareDto.getShareUserId()));
        infoQuery.setFileIdArray(pathArray);

        infoQuery.setFolderType(FileFolderTypeEnums.FOLDER.getType());

        String orderBy = "field(file_id,\"" + org.apache.commons.lang3.StringUtils.join(pathArray, "\",\"") + "\")";//拼凑根据目录id的顺序返回
        //+转义字符
        infoQuery.setOrderBy(orderBy);
        //查询出来的是一个集合类型
        List<FileInfo> fileInfoList = fileInfoService.findListByParam(infoQuery);

        return R.success(fileInfoList);

    }

    private SessionShareDto checkShare(HttpSession session, String shareId) {
        SessionShareDto shareDto = (SessionShareDto) session.getAttribute(Constants.SESSION_SHARE_KEY + shareId);;
        if (null == shareDto) {
            throw  new BusinessException(ResponseCodeEnum.CODE_903);
        }
        if (shareDto.getExpireTime() != null && new Date().after(shareDto.getExpireTime())) {
            throw new BusinessException(ResponseCodeEnum.CODE_902);
        }
        return shareDto;
    }


}